package org.jeecg.modules.hc.utils;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wechat.pay.contrib.apache.httpclient.exception.NotFoundException;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.jeecg.modules.hc.entity.*;
import org.jeecg.modules.hc.enums.HcCompanyOrderStateEnum;
import org.jeecg.modules.hc.enums.HcMerchantSettlementTypeEnum;
import org.jeecg.modules.hc.enums.HcOrderStateEnum;
import org.jeecg.modules.hc.enums.HcPaymentMethodEnum;
import org.jeecg.modules.hc.mapper.HcMerchantSettlementMapper;
import org.jeecg.modules.hc.service.*;
import org.jeecg.modules.hc.service.impl.pojo.WXResPojo;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * author作者：lilingjie
 */
//@Component
@AllArgsConstructor
@NoArgsConstructor
public class TaskUtils implements ApplicationContextAware {

    private HcMerchantSettlementMapper merchantSettlementMapper;
    private IHcMerchantSettlementService hcMerchantSettlementService;
    private IHcMerchantService hcMerchantService;
    private IHcCompanyMerchantInfoService companyMerchantInfoService;
    private IHcCompanyInfoService companyInfoService;
    private IHcCompanyFoodOrderService companyFoodOrderService;
    private IHcCompanyMerchantSettlementService companyMerchantSettlementService;
    private IHcCompanyMerchantSettingService companyMerchantSettingService;
    private IHcCompanyFoodListService companyFoodListService;
    private IHcOrderService orderService;
    private IHcWxPayService wxPayService;
    private IHcAliPayService aliPayService;


    @Value("${wx.pay.privateKeyPath}")
    private String privatekeypath ;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.merchantSettlementMapper = applicationContext.getBean(HcMerchantSettlementMapper.class);
        this.hcMerchantSettlementService = applicationContext.getBean(IHcMerchantSettlementService.class);
        this.hcMerchantService = applicationContext.getBean(IHcMerchantService.class);
        this.companyMerchantInfoService = applicationContext.getBean(IHcCompanyMerchantInfoService.class);
        this.companyFoodOrderService = applicationContext.getBean(IHcCompanyFoodOrderService.class);
        this.companyMerchantSettlementService = applicationContext.getBean(IHcCompanyMerchantSettlementService.class);
        this.companyInfoService = applicationContext.getBean(IHcCompanyInfoService.class);
        this.companyMerchantSettingService = applicationContext.getBean(IHcCompanyMerchantSettingService.class);
        this.companyFoodListService = applicationContext.getBean(IHcCompanyFoodListService.class);
        this.orderService = applicationContext.getBean(IHcOrderService.class);
        this.wxPayService = applicationContext.getBean(IHcWxPayService.class);
        this.aliPayService = applicationContext.getBean(IHcAliPayService.class);


    }

//    @Scheduled(cron = "0 */1 * * * ?")
    //查询pc订单支付情况
    public void checkPcOrder(){
        System.out.println("查询订单支付情况...");
        List<HcOrder> orderList = orderService.list(new LambdaQueryWrapper<HcOrder>().in(HcOrder::getPaymentMethod, HcPaymentMethodEnum.PC_WX, HcPaymentMethodEnum.PC_ZFB).eq(HcOrder::getState, HcOrderStateEnum.WAIT));
        if (!CollectionUtils.isEmpty(orderList)){
            orderList.forEach(o -> {
                if (o.getPaymentMethod().equals(HcPaymentMethodEnum.PC_WX)){//微信扫码支付
                    HcWxPay hcWxPay = wxPayService.getById(o.getPaymentId());
                    //微信支付对象
                    HcWxPay wxPay = orderService.queryNativePay(hcWxPay.getOutTradeNo());
                    if (null == wxPay || !wxPay.getTradeState().equals("SUCCESS")){//未支付
                        Integer callbackQueryTimes = o.getCallBackQueryTimes();
                        o.setCallBackQueryTimes(callbackQueryTimes + 1);
                        if (o.getCallBackQueryTimes() >= 10){
                            o.setState(HcOrderStateEnum.CANCELED);
                        }
                        orderService.updateById(o);
                    }
                }else if (o.getPaymentMethod().equals(HcPaymentMethodEnum.PC_ZFB)){
                    HcAliPay hcAliPay = aliPayService.getById(o.getPaymentId());
                    try {
                        HcAliPay aliPay = aliPayService.queryAliPayRes(hcAliPay.getOutTradeNo());
                        if (null == aliPay || !aliPay.getTradeStatus().equals("TRADE_SUCCESS")){//未支付
                            Integer callbackQueryTimes = o.getCallBackQueryTimes();
                            o.setCallBackQueryTimes(callbackQueryTimes + 1);
                            if (o.getCallBackQueryTimes() >= 10){//10分钟未付款，取消订单
                                o.setState(HcOrderStateEnum.CANCELED);
                            }
                            orderService.updateById(o);
                        }
                    } catch (AlipayApiException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        System.out.println("查询订单支付情况完成");
    }

    // 添加定时任务  每10分钟查询一次账单
//    @Scheduled(cron = "0 */10 * * * ?")
    public void doTask(){
        System.out.println("每10分钟查询一次结算回调");
        //查询商家结算正在进行中得结算
        //个人订单
        List<HcMerchantSettlement> hcMerchantSettlements= merchantSettlementMapper.getHcMerchantSettlementByType(HcMerchantSettlementTypeEnum.SETTLING)
                .stream().filter(h->h.getCallbackQueryTimes() < 72)//12个小时的轮询
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(hcMerchantSettlements)){
            hcMerchantSettlements.forEach(h ->{
                // 查询转账是否成功
                String result  = null;
                try {
                    result = HttpUtil.getTransBatRequest(
                            "https://api.mch.weixin.qq.com/v3/transfer/batches/out-batch-no"+"/"+h.getOutNo()+"?need_query_detail=True&detail_status=ALL",
                            "3211021750A9B797F90787395247194D1F886032",
                            "1635890587",
                            privatekeypath,"/v3/transfer/batches/out-batch-no"+"/"+h.getOutNo()+"?need_query_detail=True&detail_status=ALL");
                } catch (NotFoundException e) {
                    e.printStackTrace();
                }
                WXResPojo wxResPojo = JSONObject.parseObject(result, WXResPojo.class);
                // 转账明细
//                    TransferDetail transfer_batch = wxResPojo.getTransfer_batch();
                if (wxResPojo.getTransfer_detail_list()!=null){
                    wxResPojo.getTransfer_detail_list().forEach(t ->{
                        if (t.getDetail_status().equals("FAIL")){
                            // TODO 查明细 查询失败原因 更新数据库信息
                            hcMerchantSettlementService.updateById(new HcMerchantSettlement()
                                    .setId(h.getId())
                                    .setType(HcMerchantSettlementTypeEnum.FAIL)
                            );
                        }else if(t.getDetail_status().equals("SUCCESS")) {
                            hcMerchantSettlementService.updateById(new HcMerchantSettlement()
                                    .setId(h.getId())
                                    .setType(HcMerchantSettlementTypeEnum.SETTLED)
                            );
                        }
                    });
                }
                //更新查询次数
                merchantSettlementMapper.updateById(new HcMerchantSettlement().setId(h.getId()).setCallbackQueryTimes(h.getCallbackQueryTimes()+1));
            });
        }
        //企业订单
        List<HcCompanyMerchantSettlement> hcCompanyMerchantSettlementList= companyMerchantSettlementService
                .list(new LambdaQueryWrapper<HcCompanyMerchantSettlement>().eq(HcCompanyMerchantSettlement::getType,HcMerchantSettlementTypeEnum.SETTLING))
                .stream().filter(h->h.getCallbackQueryTimes() < 72)//12个小时的轮询
                .collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(hcCompanyMerchantSettlementList)){
            hcCompanyMerchantSettlementList.forEach(h ->{
                // 查询转账是否成功
                String result  = null;
                try {
                    result = HttpUtil.getTransBatRequest(
                            "https://api.mch.weixin.qq.com/v3/transfer/batches/out-batch-no"+"/"+h.getOutNo()+"?need_query_detail=True&detail_status=ALL",
                            "3211021750A9B797F90787395247194D1F886032",
                            "1635890587",
                            privatekeypath,"/v3/transfer/batches/out-batch-no"+"/"+h.getOutNo()+"?need_query_detail=True&detail_status=ALL");
                } catch (NotFoundException e) {
                    e.printStackTrace();
                }
                WXResPojo wxResPojo = JSONObject.parseObject(result, WXResPojo.class);
                // 转账明细
//                    TransferDetail transfer_batch = wxResPojo.getTransfer_batch();
                if (wxResPojo.getTransfer_detail_list()!=null){
                    wxResPojo.getTransfer_detail_list().forEach(t ->{
                        if (t.getDetail_status().equals("FAIL")){
                            // TODO 查明细 查询失败原因 更新数据库信息
                            companyMerchantSettlementService.updateById(new HcCompanyMerchantSettlement()
                                    .setId(h.getId())
                                    .setType(HcMerchantSettlementTypeEnum.FAIL)
                            );
                        }else if(t.getDetail_status().equals("SUCCESS")) {
                            companyMerchantSettlementService.updateById(new HcCompanyMerchantSettlement()
                                    .setId(h.getId())
                                    .setType(HcMerchantSettlementTypeEnum.SETTLED)
                            );
                        }
                    });
                }
                //更新查询次数
                companyMerchantSettlementService.updateById(new HcCompanyMerchantSettlement().setId(h.getId()).setCallbackQueryTimes(h.getCallbackQueryTimes()+1));
            });
        }
    }

    // 每周三自动结算
//    @Scheduled(cron = "0 0 12 ? * WED")
    public void autoSettle(){
        //获取上周开始的时间
        Date beginDayOfLastWeek = getBeginDayOfLastWeek();

//        System.out.println("开始时间："+beginDayOfLastWeek);
        //获取上周的结束时间
        Date endDayOfLastWeek = getEndDayOfLastWeek();
//        System.out.println("结束时间："+endDayOfLastWeek);

        AtomicInteger i = new AtomicInteger();

        //获取所有设置自动结算的店铺
        List<HcMerchant> allAutoSettleMerchant = hcMerchantService.getAllAutoSettleMerchant();
        if (!CollectionUtils.isEmpty(allAutoSettleMerchant)){
            //根据商户id获取对应的结算信息
            allAutoSettleMerchant.forEach(a->{
                List<HcMerchantSettlement> list = hcMerchantSettlementService.list(
                        new LambdaQueryWrapper<HcMerchantSettlement>()
                                .eq(HcMerchantSettlement::getMerchantId, a.getId())
                                .in(HcMerchantSettlement::getType, Arrays.asList(HcMerchantSettlementTypeEnum.UNSETTLED
                                        ,HcMerchantSettlementTypeEnum.SETTLING
                                        ,HcMerchantSettlementTypeEnum.FAIL))
                                .orderByDesc(HcMerchantSettlement::getSettlementDate)
                );
                //售后
//            list.forEach( l -> {
//                if (l.getSettlementDate() != null){
//                    String beginTime = "";
//                    String endTime = "";
//                    Calendar instance = Calendar.getInstance();
//                    instance.setTime(l.getSettlementDate());
//                    beginTime = DateUtils.formatDate(instance.getTime(), "yyyy-MM-dd") + " 18:00:01";
//                    instance.add(Calendar.DAY_OF_MONTH, +1);
//                    endTime = DateUtils.formatDate(instance.getTime(), "yyyy-MM-dd") + " 18:00:00";
//                    final BigDecimal[] finalSettlementAmount = {new BigDecimal(String.valueOf(l.getSettlementAmount()))};
//                    //根据id查询售后信息
////                    List<HcAfterSales> list1 = hcAfterSalesService.list(
////                            new LambdaQueryWrapper<HcAfterSales>()
////                                    .eq(HcAfterSales::getMerchantId, l.getMerchantId())
////                                    .between(HcAfterSales::getCreateTime,beginTime,endTime)
////                    );
////                    if (list1!=null){
////                        list1.forEach( l1 -> {
////                            if (l1.getDeductMerchantAmount() != null)
////                                finalSettlementAmount[0] =  finalSettlementAmount[0].subtract(new BigDecimal(String.valueOf(l1.getDeductMerchantAmount())));
////                        });
////                    }
//                    l.setSettlementAmount(finalSettlementAmount[0]);
//                }
//            });

                //上一周需要结算的结算数据
                //compareTo  如果Date在date参数之后，则返回值大于0，如果Date在date参数之前，则返回值小于0。
                Stream<HcMerchantSettlement> hcMerchantSettlements = list.stream().filter(l -> l.getSettlementDate().compareTo(beginDayOfLastWeek) >= 0 && l.getSettlementDate().compareTo(endDayOfLastWeek) <= 0);
                //商家批次单号 长度 1~32
                String outNo = IdUtil.getSnowflake(0, 0).nextIdStr();
                //openId
                final String[] openId = {""};
                //备注
                final String[] remarks = {""};
                //转账总金额
                final BigDecimal[] totalSettlementAmount = {new BigDecimal(0)};
                hcMerchantSettlements.forEach(h -> {
                    HcMerchant hcMerchant = hcMerchantService
                            .getById(hcMerchantSettlementService
                                    .getById(h.getId()).getMerchantId());
                    if (hcMerchant.getStoreName().contains("•")){
                        String storeName = hcMerchant.getStoreName().replace("•", "");
                        remarks[0] = storeName +":";
                    }else {
                        remarks[0] = hcMerchant.getStoreName()+":";
                    }
//                System.out.println(h.getSettlementAmount());
                    totalSettlementAmount[0] = totalSettlementAmount[0].add(new BigDecimal(String.valueOf(h.getSettlementAmount())));
                    openId[0] = hcMerchant.getOpenId();
                    hcMerchantSettlementService.updateById(new HcMerchantSettlement()
                            .setId(h.getId())
                            .setSettlementAmount(h.getSettlementAmount())
                            .setOutNo(outNo)
                            .setType(HcMerchantSettlementTypeEnum.SETTLING)
                    );
                });
                i.getAndIncrement();
//            System.out.println("第"+i.get()+"家");
//            System.out.println(a.getStoreName()+"转账总金额："+totalSettlementAmount[0]);
                BigDecimal divide = totalSettlementAmount[0].divide(new BigDecimal(1999),0,BigDecimal.ROUND_UP);
                try {
                    //超2000分批结算
                    if (totalSettlementAmount[0].compareTo(new BigDecimal(2000)) == 1){
                        int flag = 0;
                        do {
                            flag+=1;
                            String remark = "";
                            if (totalSettlementAmount[0].compareTo(new BigDecimal(1999)) == 1){
                                //商家批次单号 长度 1~32
                                String outNo1 = IdUtil.getSnowflake(0, 0).nextIdStr();
                                // 转账备注
                                remark = " 转账1999元("+ flag+"/"+divide+")";
//                            System.out.println(remarks[0] + remark);
                                hcMerchantService.transferToMerchant(openId[0], new BigDecimal(1999), outNo1,remarks[0] + remark);
                                totalSettlementAmount[0] = totalSettlementAmount[0].subtract(new BigDecimal(1999));
                            }else {
                                // 转账备注
                                remark = " 转账"+totalSettlementAmount[0]+"元("+ flag+"/"+divide+")";
//                            System.out.println(remarks[0] + remark);
                                hcMerchantService.transferToMerchant(openId[0], totalSettlementAmount[0], outNo,remarks[0] + remark);
                                totalSettlementAmount[0] = totalSettlementAmount[0].subtract(new BigDecimal(1999));
                            }
                        }while (totalSettlementAmount[0].compareTo(new BigDecimal(0)) == 1);
                    }else {
                        //未超2000的直接结算
                        remarks[0] += totalSettlementAmount[0]+"元";
                        //转账给商户
                        hcMerchantService.transferToMerchant(openId[0], totalSettlementAmount[0], outNo,remarks[0]);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }

    //每天下午18:30，将企业未完结的订单全部修改未已完成
//        @Scheduled(cron = "0/20 * * * * ?") // 测试
//    @Scheduled(cron = "0 30 18 * * ?")
    public void completedCompanyOrder(){
        companyFoodOrderService.updateByOrderNum();
    }

    //每天下午19:30，重置限购商品
//        @Scheduled(cron = "0/20 * * * * ?") // 测试
//    @Scheduled(cron = "0 30 19 * * ?")
    public void resetLimitFood(){
        //将限购还原
        companyFoodListService.resetBuyedNum();
    }


//    @Scheduled(cron = "0 5 19 * * ?")//每天下午19:05，计算商户的企业订单结算信息
//    @Scheduled(cron = "0/20 * * * * ?") // 测试
    public void fixCompanyOrderSettlement(){
        System.out.println("----------------------------------------");
        Calendar maxCalendar = Calendar.getInstance();
        Date today = new Date(System.currentTimeMillis());

        Date yesterday = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String todayString = dateFormat.format(today);
        String yesterdayString = dateFormat.format(yesterday);


//        String todayString = "2023-09-13";
//        String yesterdayString = "2023-09-12";

        //获取当天的订单信息
        List<HcCompanyFoodOrder> hcCompanyFoodOrders = companyFoodOrderService.list(new LambdaQueryWrapper<HcCompanyFoodOrder>()
                .between(HcCompanyFoodOrder::getCreateTime, yesterdayString + " 19:00:00", todayString + " 19:00:00")
                .eq(HcCompanyFoodOrder::getState, HcCompanyOrderStateEnum.COMPLETED));
        if (!CollectionUtils.isEmpty(hcCompanyFoodOrders)){
            //获取所有商户信息
            List<String> merchantIds = hcCompanyFoodOrders.stream().map(HcCompanyFoodOrder::getMerchantId).distinct().collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(merchantIds)){
                merchantIds.forEach(m -> {
                    //获取所有企业信息
                    List<String> companyIds = hcCompanyFoodOrders.stream().filter(c->c.getMerchantId().equals(m)).map(HcCompanyFoodOrder::getCompanyId).distinct().collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(companyIds)){
                        companyIds.forEach( c ->{
                            //获取昨天的订单
                            LambdaQueryWrapper<HcCompanyFoodOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
                            orderLambdaQueryWrapper
                                    .eq(HcCompanyFoodOrder::getCompanyId,c)
                                    .eq(HcCompanyFoodOrder::getMerchantId,m)
                                    .between(HcCompanyFoodOrder::getCreateTime,yesterdayString+" 19:00:00",todayString+" 19:00:00")
                                    .eq(HcCompanyFoodOrder::getState, HcCompanyOrderStateEnum.COMPLETED);
                            List<HcCompanyFoodOrder> companyFoodOrders = companyFoodOrderService.list(orderLambdaQueryWrapper);
                            if (!CollectionUtils.isEmpty(companyFoodOrders)){
                                //获取商户对应得企业订单
                                HcCompanyMerchantSettlement hcCompanyMerchantSettlement = new HcCompanyMerchantSettlement()
                                        .setCreateTime(new Date())
                                        .setCreateBy("system")
                                        .setMerchantId(m)
                                        .setCompanyId(c)
                                        .setSettlementDate(maxCalendar.getTime())
                                        .setType(HcMerchantSettlementTypeEnum.UNSETTLED);
                                BigDecimal totalIncome = new BigDecimal("0");
                                for (HcCompanyFoodOrder companyFoodOrder : companyFoodOrders) {
                                    JSONObject foodInfo = JSONObject.parseObject(companyFoodOrder.getFoodInfo());
                                    //商品数量
                                    Integer foodNum = (Integer) foodInfo.get("foodNum");

                                    JSONObject foodObject = foodInfo.getJSONObject("food");
                                    HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);
                                    BigDecimal foodPrice = new BigDecimal(0);
                                    if (hcCompanyFoodList.getCooperatePrice()==null || hcCompanyFoodList.getCooperatePrice().compareTo(new BigDecimal(0)) == 0){
                                        //获取门店价格
                                        HcCompanyMerchantSetting companyMerchantSetting = companyMerchantSettingService.getOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
                                                .eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
                                                .eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
                                        if (null == companyMerchantSetting){
                                            companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0)).setSalePrice(new BigDecimal(0));
                                        }
                                        if (companyMerchantSetting.getMerchantCooperatePrice()==null||companyMerchantSetting.getMerchantCooperatePrice().compareTo(new BigDecimal(0))==0){
                                            //获取企业合作价格
                                            HcCompanyInfo hcCompanyInfo = companyInfoService.getOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, hcCompanyFoodList.getCompanyId()));
                                            foodPrice = foodPrice.add(hcCompanyInfo.getMerchantPrice().multiply(new BigDecimal(foodNum)));
                                        }else {
                                            foodPrice = foodPrice.add(companyMerchantSetting.getMerchantCooperatePrice().multiply(new BigDecimal(foodNum)));
                                        }
                                    }else {
                                        foodPrice = foodPrice.add(hcCompanyFoodList.getCooperatePrice().multiply(new BigDecimal(foodNum)));
                                    }
                                    totalIncome = totalIncome.add(foodPrice);
                                }
                                hcCompanyMerchantSettlement.setSettlementAmount(totalIncome);

                                //找到当天的结算数据
                                HcCompanyMerchantSettlement one = companyMerchantSettlementService.getOne(new LambdaQueryWrapper<HcCompanyMerchantSettlement>()
                                        .eq(HcCompanyMerchantSettlement::getCompanyId, c)
                                        .eq(HcCompanyMerchantSettlement::getMerchantId, m)
                                        .eq(HcCompanyMerchantSettlement::getSettlementDate, todayString));
                                if (null!= one){
                                    one.setSettlementAmount(one.getSettlementAmount().add(hcCompanyMerchantSettlement.getSettlementAmount()));
                                    companyMerchantSettlementService.updateById(one);
                                }else {
                                    companyMerchantSettlementService.save(hcCompanyMerchantSettlement);
                                }
                            }
                        });
                    }
                });
            }
        }
    }


    // 获取某个日期的开始时间
    public static Timestamp getDayStartTime(Date d) {
        Calendar calendar = Calendar.getInstance();
        if (null != d)
            calendar.setTime(d);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return new Timestamp(calendar.getTimeInMillis());
    }

    // 获取上周的开始时间
    public static Date getBeginDayOfLastWeek() {
        Date date = new Date();
        if (date == null) {
            return null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
        if (dayofweek == 1) {
            dayofweek += 7;
        }
        cal.add(Calendar.DATE, 2 - dayofweek - 7);
        return getDayStartTime(cal.getTime());
    }

    // 获取某个日期的结束时间
    public static Timestamp getDayEndTime(Date d) {
        Calendar calendar = Calendar.getInstance();
        if (null != d)
            calendar.setTime(d);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return new Timestamp(calendar.getTimeInMillis());
    }

    // 获取上周的结束时间
    public static Date getEndDayOfLastWeek() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getBeginDayOfLastWeek());
        cal.add(Calendar.DAY_OF_WEEK, 6);
        Date weekEndSta = cal.getTime();
        return getDayEndTime(weekEndSta);
    }
}
